var exec = require('child_process').exec;

function doNothing() {
}

function sleep(milliSeconds) {
	var time = new Date().getTime();

	while(new Date().getTime() < time + milliSeconds);
}

function printHtml(res, html) {
	// write the response
	res.writeHead(200, {
		'Content-Type': 'text/html;charset=utf-8'
	});
	res.write(html);
	res.end();
}

function printText(res, text) {
	// write the response
	res.writeHead(200, {
		'Content-Type': 'text/plain;charset=utf-8'
	});
	res.write(text);
	res.end();
}

handler = {
	'/favicon.ico': doNothing,
	'/': function (req, res) {
		printText(res, 'The path is "/" ' + new Date());
	},
	'/user': function (req, res) {
		printText(res, 'The path is "/user" ' + new Date());
	},
	'/image': function (req, res) {
		printText(res, 'The path is "/image" ' + new Date());
	},
	'/files': function (req, res) {
		exec('ls -lah', function (error, stdout, stderr) {
			printText(res, stdout);
		})
	},
	'/post': function (req, res) {
		var body = '<html>'+
				'<head>'+
				'<meta http-equiv="Content-Type" content="text/html; '+
				'charset=UTF-8" />'+
				'</head>'+
				'<body style="background: #efefef;">'+
				'<form action="/upload" method="post">'+
				'<textarea name="text" rows="20" cols="60"></textarea><br>'+
				'<input type="submit" value="Submit text" />'+
				'</form>'+
				'</body>'+
				'</html>';
		printHtml(res, body);
	},
	'/upload': function (req, res) {
		printText(res, req.postData);
	}
};

exports.handler = handler;